package structural.flyweight;

import java.util.HashMap;
import java.util.Map;

/**
 * @ClassName: FlyweightFactory
 * @Description: 享元工厂类：用于创建和管理享元对象
 * @Author: liu-hao
 * @Date: 2023-04-09 20:35
 * @Version: 1.0
 **/
public class FlyweightFactory {
    private Map<String, Flyweight> flyweights = new HashMap<>();

    public Flyweight getFlyweight(String key) {
        // 当客户端请求相同的 key 参数时，将返回同一个 ConcreteFlyweight 对象，从而实现了对象的共享
        Flyweight flyweight = flyweights.get(key);
        if (flyweight == null) {
            flyweight = new ConcreteFlyweight(key);
            flyweights.put(key, flyweight);
        }
        return flyweight;
    }
}
